package com.grouuu.factory;

import com.grouuu.tile.TileGraphic;
import nme.Assets;
import nme.display.BitmapData;
import starling.textures.Texture;
import starling.textures.TextureAtlas;

/**
 * ...
 * @author Grouuu
 */

class SpriteFactory 
{
	private var asset:BitmapData;
	private var map:flash.xml.XML;
	private var atlas:TextureAtlas;
	private var texture:Texture;
	
	private var bufferTextures:Array<flash.Vector<Texture>>;
	private var bufferTileGraphic:Hash<flash.Vector<TileGraphic>>;

	public function new() 
	{
		bufferTextures = new Array<flash.Vector<Texture>>();
		bufferTileGraphic = new Hash<flash.Vector<TileGraphic>>();
		
		asset = Assets.getBitmapData("tiles/texture.png");
		map = new flash.xml.XML(Assets.getText("tiles/texture.xml"));
		texture = Texture.fromBitmapData(asset);
		atlas = new TextureAtlas(texture, map);
	}
	
	public function getTileGraphic(idTile:Int):TileGraphic
	{
		if (bufferTileGraphic.get(Std.string(idTile)) != null)
		{
			if (bufferTileGraphic.get(Std.string(idTile)).length > 0)
			{
				var tile:TileGraphic = bufferTileGraphic.get(Std.string(idTile)).shift();
				
				tile.start();
				
				return tile;
			}
		}
		
		var tex:flash.Vector<Texture>;
		
		if (bufferTextures[idTile] == null)
		{
			tex = atlas.getTextures(getTextureName(idTile));
			
			bufferTextures[idTile] = tex;
		}
		else
			tex = bufferTextures[idTile];
		
		return new TileGraphic(idTile, tex);
	}
	
	private function getTextureName(idTile:Int):String
	{
		var idTexture:String = "";
		
		switch(idTile)
		{
			case 0: idTexture = "tile_barrier_horizon";
			case 1: idTexture = "tile_barrier_horizon";
			case 2: idTexture = "tile_barrier_corner_top_right";
			case 3: idTexture = "tile_barrier_right";
			case 4: idTexture = "tile_barrier_corner_bot_right";
			case 5: idTexture = "tile_barrier_corner_bot_left";
			case 6: idTexture = "tile_barrier_left";
			case 7: idTexture = "tile_barrier_corner_top_left";
			case 8: idTexture = "tile_grass";
		}
		
		return idTexture;
	}
	
	public function deleteTileGraphic(tile:TileGraphic):Void
	{
		if (bufferTileGraphic.get(Std.string(tile.idTile)) == null)
			bufferTileGraphic.set(Std.string(tile.idTile), new flash.Vector<TileGraphic>());
		
		tile.reset();
		
		bufferTileGraphic.get(Std.string(tile.idTile)).push(tile);
	}
}